import api from '@/api'
const state = () => ({
  //获取数据URL
  url: {
    "submit": ""
  },
  form: {},
  fields: {}
})

function in_array(search, array) {
  for (var i in array) {
    if (array[i] == search) {
      return true;
    }
  }
  return false;
}

const mutations = {
  setForm: (state, {key,value}) => {
    state.form[key] = state.fields[key] = value;
    console.log('state',state.form);
  },
  setField: (state, { key, value }) => {
    //console.log("查看是", [key, value]);
    let fields = state.form;
    if (fields.hasOwnProperty(key)) {
      state.form[key] = value
    }
  },
  //重置表单
  resetForm: (state) => {
    state.form = state.fields
  },
  // 设置url
  setURL: (state,value) =>{
    state.url.submit = value;
  },
  // 回调数据
  retData: (state,callback) => {
    callback(state.form);
  }
}

const actions = {
  //表单初始化
  initialize({ dispatch, commit, state }, {key,config}) {
    console.log('from',[key,config])
    let form = {};
    config.forEach(data => {
      if (Array.isArray(data)) {
        data.forEach(item => {
          if (item.hasOwnProperty('type') && !in_array(item.type, ['title', 'button'])) {
            let field = {};
            let key = item['field'];
            let value = item['default'];
            field[key] = value;
            //对象合并
            Object.assign(form, field);
          }
        })
      } else {
        if (data.hasOwnProperty('type') && !in_array(data.type, ['title', 'button'])) {
          let field = {};
          let key = data['field'];
          let value = data['default'];
          field[key] = value;
          //对象合并
          Object.assign(form, field);
        }
      }
    })
    commit('setForm', {key:key,value:form})
  },
  //编辑表单数据
  editformData({ dispatch, commit, state }, formData) {
    commit('setForm', formData)
  },
  // 表单提交
  submitFormData({ dispatch, commit, state }, callback) {
    let model = state.url.submit.model;
    let action = state.url.submit.action;
    api[model][action](state.form).then(response => {
      callback();
      console.log("返回信息", response);
      //提交完成后重置表单
      commit('resetForm')
    });
  },


  /**
   * 获取下拉，单选，多选的选项数据
   * @param  {[type]} state          [description]
   * @param  {[type]} options.model  [description]
   * @param  {[type]} options.action [description]
   * @return {[type]}                [description]
   */
  getOptionData(state,{model,action,callback}){
    api[model][action]({}).then(response =>{
      if(typeof callback == 'function'){
        callback(response);
      }
    });
  }
}

export default {
  state,
  mutations,
  actions
}
